#!/bin/sh

# Part of Zombie Navigator
# Copyright © 2015  Zombie Navigator Developers

mylog () {
	echo "[`date`] $@" >&2
}

dir="`dirname "$0"`"
dir="`cd "$dir";pwd`"
cd "$dir/src"

. ../version_info


# Create .xpi
while [ "$#" -gt 0 ] ; do
	case "$1" in
		--minify-js)
			minify_js=1
			;;
		--help)
			echo "Usage: $0 [--minify-js]"
			exit
			;;
		--version)
			echo "Will build: '$addon_version'"
			exit
			;;
	esac
	shift
done


mylog "$addon_id version $addon_version build script"

buildsDir="$dir/builds"
buildTmpDir="$dir/.build"

mkdir -p "$buildsDir"
rm -rf "$buildTmpDir"

cd ..
cp -rf src "$buildTmpDir"
cd "$buildTmpDir"

mylog "Optimizing files..."

find . -type f \( -name '*.html' -or -name '*.js' \) -execdir sh -c 'egrep -v "^\s*$|vim:" "$1" > "$1.tmp" && mv -f "$1.tmp" "$1" || rm -f "$1.tmp"' -- {} \;

find . -type f -name '*.css' -execdir sh -c 'egrep -v "^\s*$|vim:" "$1" | tr -d "\t\n" | perl -pe "s/\s*([{:>+,])\s*/\1/g ; s/;}/}/g" > "$1.tmp" && mv -f "$1.tmp" "$1" || rm -f "$1.tmp"' -- {} \;

find . -type f -name '*.json' -execdir sh -c 'egrep -v "^\s*$" "$1" | sed "s/^ *//" | tr -d "\n" > "$1.tmp" && mv -f "$1.tmp" "$1" || rm -f "$1.tmp"' -- {} \;


[ "$minify_js" ] && {
	mylog "EXPERIMENTAL: Doing JS minification..."
	mylog "This may result in problems!"
	find . -type f -name '*.js' -exec sh -c 'echo "Compressing: $1" ; ../bin/estidy < "$1" > "$1.tmp" && mv -f "$1.tmp" "$1" || rm -f "$1.tmp"' -- {} \;
} || {
	mylog "Skipping JS minification!"
}

du -a -h --apparent-size --max-depth 1 || du -ahd1


mylog "Building the addon..."
mylog "Please ignore JPM warnings about the 'sember' (if any) (NOT relevant for stable release versions)"
mylog "Because we use '~' for prereleases (for consistence with GNU/Linux conventions)"

../bin/build || {
	mylog "[ERROR] JPM: Failed"
	exit 1
}

if which advzip >/dev/null 2>&1 ; then
	# AdvanceCOMP available
	mylog "Recompressing..."
	advzip -z -4 -i 200 ./*.xpi
else
	mylog "NOTE: Skipping recompression (AdvanceCOMP needed)..."
fi

mylog "Saving the archive..."
targetDir="$buildsDir/`date +%s`"
[ "$minify_js" ] && targetDir="$targetDir.min-js"
mkdir -p "$targetDir"
mv -b -v ./*.xpi "$targetDir"/ || mv -n -v ./*.xpi "$targetDir"/

cd ..
rm -rf "$buildTmpDir"

mylog "Done? ($addon_id $addon_version)"


# vim: ts=4 noet ai

